/**
 * Created by wry on 2014/12/11.
 */

var questionService = require('../services/questionService');
var messageUtil = require('../common/utils/messageUtil');
var toolUtil = require('../common/utils/toolUtil');
var shareService = require('../services/mobile/sharesService');
var md5 = require('MD5');
var redisKey = require('../config/redisKey');

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   start   */
var userService = require('../services/userService');
exports.postQuestionNew = function (req, res) {
    var token = req.params.token;

    userService.getUserGagOrNotService(token, function (err, results) {
        if (err) {
            logger.error("Failed to postQuestionNew - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to postQuestionNew - " + err.message));
        } else {
            var gagOrNot = results._doc.gagOrNot;
            if(gagOrNot) {
                logger.error("Failed to postQuestionNew - " + gagOrNot);
                res.json(messageUtil.composeFailedMessage(req, "您被禁言了!" + ""));
            } else {
                logger.debug("Succeeded to postQuestionNew! - " + gagOrNot);


                res.header("Access-Control-Allow-Origin", "*");
                var input = req.body;

                if (input.category == 'activity') {
                    input.category = 'share'
                }

                if (input.category == 'free') {
                    input.category = 'secondhand'
                }

                toolUtil.uploadImageService(null, null, req, function (err, images) {
                    if (err) {
                        logger.error('postQuestionNew - uploadImage - ' + err.message);
                        res.json(messageUtil.composeFailedMessage(req, '发起问题失败'));
                    } else {
                        var tempImages = new Array();
                        var k = 0;
                        for (var i = 0; i < images.length; i++) {
                            if (images[i] != null)
                                tempImages[k++] = {
                                    "imageURL": images[i]
                                }
                        }
                        input['images'] = tempImages;

                        if (input.aroundCommunity != null && typeof input.aroundCommunity == 'string') {
                            input.aroundCommunity = [input.aroundCommunity];
                        }

                        questionService.postQuestionNewService(token, input, function (err, result) {
                            if (err) {
                                logger.error('postQuestionNew - - ' + err.message);
                                res.json(messageUtil.composeFailedMessage(req, '发起问题失败'));
                                toolUtil.deleteImage(images);
                            } else {
                                var data = {
                                    _id: result.question._id
                                };
                                if (input.category === 'question')
                                    toolUtil.hessianInvokeAddScore(token, input.category == 'question' ? 23 : 3, null, function (score) {
                                        if (score != null && score.currentValue != null) {
                                            data.currentValue = score.currentValue;
                                            data.changeValue = score.changeValue;
                                        }
                                        if (input.images != null) {
                                            data.images = input.images;
                                        }
                                        data.dateCreated = result.question.dateCreated;

                                        data.shareData = shareService.shareDataService(result.communityName + "的" + questionCategory[result.question.category],
                                            result.question.desc, result.question.images, 'question');

                                        res.json(messageUtil.composeSucceededMessage(req, null, data));

                                        var key = 'catch:q:all:' + result.question.community;
                                        var categoryKey = 'catch:q:category:' + input.category + ':' + result.question.community;
                                        redisClient.del(key);
                                        redisClient.del(categoryKey);

                                        //统计用户数据
                                        redisClient.HINCRBY(redisKey.getUserDataStatisticKey(token), 'question', 1);

                                        //推送
                                        questionService.pushQuestionService(result.user, result.tag, result.tags, result.question, result.input, result.pushFlag);

                                    });
                            }
                        });
                    }
                });
            }
        }
    });
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   end   */

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   start   */
/**
 * 增加提问
 */
exports.postQuestion = function (req, res) {

    var token = req.params.token;

    userService.getUserGagOrNotService(token, function (err, results) {
        if (err) {
            logger.error("Failed to postQuestion - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to postQuestion - " + err.message));
        } else {
            var gagOrNot = results._doc.gagOrNot;
            if(gagOrNot) {
                logger.error("Failed to postQuestion - " + gagOrNot);
                res.json(messageUtil.composeFailedMessage(req, "您被禁言了!" + ""));
            } else {
                logger.debug("Succeeded to postQuestion! - " + gagOrNot);

                var input = req.body;

                questionService.postQuestionService(token, input, function (err, results) {
                    if (err) {
                        logger.error("Failed to post question - " + err.message);
                        res.json(messageUtil.composeFailedMessage(req, "Failed to post question - " + err.message));
                    } else {
                        logger.debug("Succeeded to post a question! - " + results._id);

                        res.json(messageUtil.composeSucceededMessage(req, null, results));

                    }
                });
            }
        }
    });
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   start   */
/**
 * 上传问题图片
 */
exports.uploadQuestionImages = function (req, res) {

    var token = req.params.token;

    userService.getUserGagOrNotService(token, function (err, results) {
        if (err) {
            logger.error("Failed to uploadQuestionImages - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to uploadQuestionImages - " + err.message));
        } else {
            var gagOrNot = results._doc.gagOrNot;
            if(gagOrNot) {
                logger.error("Failed to uploadQuestionImages - " + gagOrNot);
                res.json(messageUtil.composeFailedMessage(req, "您被禁言了!" + ""));
            } else {
                logger.debug("Succeeded to uploadQuestionImages! - " + gagOrNot);


                var objectName = 'question';
                var questionId = req.params.questionId;
                toolUtil.uploadImageService(objectName, questionId, req, function (err, images) {
                    if (err) {
                        res.json(messageUtil.composeFailedMessage(req, 'Failed to upload question Images... - ' + err.message));
                    } else {
                        var tempImages = new Array();
                        var k = 0;
                        for (i = 0; i < images.length; i++) {
                            if (images[i] != null)
                                tempImages[k++] = {
                                    "imageURL": images[i]
                                }
                        }
                        questionService.setImagesToQuestion(questionId, tempImages, function (err, result) {
                            if (err || tempImages == null) {
                                res.json(messageUtil.composeFailedMessage(req, 'Failed to upload question Images... - ' + err.message));
                            } else {
                                res.json(messageUtil.composeSucceededMessage(req, null, null));
                            }
                        });
                    }
                });
            }
        }
    });
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   end   */

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   start   */
/**
 * 修改问题
 */
exports.updateQuestion = function (req, res) {
    var token = req.params.token;

    userService.getUserGagOrNotService(token, function (err, results) {
        if (err) {
            logger.error("Failed to updateQuestion - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to updateQuestion - " + err.message));
        } else {
            var gagOrNot = results._doc.gagOrNot;
            if(gagOrNot) {
                logger.error("Failed to updateQuestion - " + gagOrNot);
                res.json(messageUtil.composeFailedMessage(req, "您被禁言了!" + ""));
            } else {
                logger.debug("Succeeded to updateQuestion! - " + gagOrNot);


                var questionId = req.params.questionId;
                var input = req.body;

                logger.debug('Updating a Question: ' + questionId);

                questionService.updateQuestionService(questionId, input, function (err, result) {
                    if (err) {
                        logger.error('Exception happened when trying to update the question data...!');
                        res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to update the question data...!'));
                    } else {
                        res.json(messageUtil.composeSucceededMessage(req, null, null));
                    }
                });

            }
        }
    });
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   end   */

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   start   */
/**
 * 举报问题
 */
exports.reportQuestion = function (req, res) {
    var token = req.params.token;

    userService.getUserGagOrNotService(token, function (err, results) {
        if (err) {
            logger.error("Failed to reportQuestion - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to reportQuestion - " + err.message));
        } else {
            var gagOrNot = results._doc.gagOrNot;
            if(gagOrNot) {
                logger.error("Failed to reportQuestion - " + gagOrNot);
                res.json(messageUtil.composeFailedMessage(req, "您被禁言了!" + ""));
            } else {
                logger.debug("Succeeded to reportQuestion! - " + gagOrNot);

                var questionId = req.params.questionId;
                questionService.reportQuestionService(token, questionId, function (err, result) {
                    if (err) {
                        logger.error('Exception happened when trying to update the question data...!' + err.message);
                        res.json(messageUtil.composeSucceededMessage(req, '举报成功，请等待审核', null, 4001));
                    } else {
                        res.json(messageUtil.composeSucceededMessage(req, '举报成功，请等待审核', null, 4001));
                    }
                })
            }
        }
    });
}
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   end   */

/*  宝宝树66小区二次改造    mod   chnef  20170821   start   */
/**
 * 举报问题新接口
 */
exports.reportQuestionNew = function (req, res) {
    var token = req.params.token;

    userService.getUserGagOrNotService(token, function (err, results) {
        if (err) {
            logger.error("Failed to reportQuestion - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to reportQuestion - " + err.message));
        } else {
            var gagOrNot = results._doc.gagOrNot;
            if(gagOrNot) {
                logger.error("Failed to reportQuestion - " + gagOrNot);
                res.json(messageUtil.composeFailedMessage(req, "您被禁言了!" + ""));
            } else {
                logger.debug("Succeeded to reportQuestion! - " + gagOrNot);

                var questionId = req.params.questionId;
                var statusFlg = req.params.statusFlg;
                questionService.reportQuestionNewService(token, questionId,statusFlg, function (err, result) {
                    if (err) {
                        logger.error('Exception happened when trying to update the question data...!' + err.message);
                        res.json(messageUtil.composeSucceededMessage(req, '举报成功，请等待审核', null, 4001));
                    } else {
                        res.json(messageUtil.composeSucceededMessage(req, '举报成功，请等待审核', null, 4001));
                    }
                })
            }
        }
    });
}
/*  宝宝树66小区二次改造    mod   chenf  20170821   end   */

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   start   */
/**
 * 删除提问
 */
// 删除
exports.deleteQuestion = function (req, res) {

    var token = req.params.token;

    userService.getUserGagOrNotService(token, function (err, results) {
        if (err) {
            logger.error("Failed to deleteQuestion - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to deleteQuestion - " + err.message));
        } else {
            var gagOrNot = results._doc.gagOrNot;
            if(gagOrNot) {
                logger.error("Failed to deleteQuestion - " + gagOrNot);
                res.json(messageUtil.composeFailedMessage(req, "您被禁言了!" + ""));
            } else {
                logger.debug("Succeeded to deleteQuestion! - " + gagOrNot);

                var questionId = req.params.questionId;
                logger.debug('Deleting a Question: ' + questionId);

                questionService.deleteQuestionService(questionId, function (err, result) {
                    if (err) {
                        logger.error('Exception happened when trying to delete the question ...!' + err.message);
                        res.json(messageUtil.composeFailedMessage(req, err.message, 4002));
                    } else {
                        res.json(messageUtil.composeSucceededMessage(req, null, null, 4002));


                        //统计用户数据
                        toolUtil.changeUserStatistics(token, result.community, 'question', -1);

                        toolUtil.putMessageSmartRankMQ({questionId: questionId, type: 7});

                        var action = (result.category == 'question' || result.category == 'secondhand') ? 28 : 14;

                        toolUtil.hessianInvokeAddScore(token, action, null, function (score) {

                        }, req.query.vcode);
                    }
                })
            }
        }
    });
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   end   */

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   start   */
/**
 * 删除提问图片
 */
exports.deleteQuestionImages = function (req, res) {
    var token = req.params.token;

    userService.getUserGagOrNotService(token, function (err, results) {
        if (err) {
            logger.error("Failed to deleteQuestionImages - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to deleteQuestionImages - " + err.message));
        } else {
            var gagOrNot = results._doc.gagOrNot;
            if(gagOrNot) {
                logger.error("Failed to deleteQuestionImages - " + gagOrNot);
                res.json(messageUtil.composeFailedMessage(req, "您被禁言了!" + ""));
            } else {
                logger.debug("Succeeded to deleteQuestionImages! - " + gagOrNot);

                var questionId = req.params.questionId;
                var images = req.body;
                logger.debug('Deleting a Question images: ' + questionId);

                questionService.deleteQuestionImagesService(questionId, images, function (err, result) {
                    if (err) {
                        logger.error('Exception happened when trying to delete the question images ...!');
                        res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to delete the question images...!'));
                    } else {
                        res.json(messageUtil.composeSucceededMessage(req, null, null));
                    }
                })
            }
        }
    });
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   end   */

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   start   */
/**
 * 回答问题
 */
exports.postReply = function (req, res) {

    var token = req.params.token;

    userService.getUserGagOrNotService(token, function (err, results) {
        if (err) {
            logger.error("Failed to postReply - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to postReply - " + err.message));
        } else {
            var gagOrNot = results._doc.gagOrNot;
            if(gagOrNot) {
                logger.error("Failed to postReply - " + gagOrNot);
                res.json(messageUtil.composeFailedMessage(req, "您被禁言了!" + ""));
            } else {
                logger.debug("Succeeded to postReply! - " + gagOrNot);

                var questionId = req.params.questionId;
                var input = req.body;

                logger.debug('Reply a question....' + questionId);

                questionService.postReplyService(token, questionId, input, function (err, result) {
                    if (err) {
                        logger.error('Exception happened when trying to postReply ...!' + err.message);
                        res.json(messageUtil.composeFailedMessage(req, err.message));
                    } else {
                        var replyId = {
                            "_id": result.replies[result.replies.length - 1]._id
                        };

                        //toolUtil.hessianInvokeAddScore(token, 'postReply', function (score) {
                        //    if (score != null && score.currentValue != null) {
                        //        replyId.currentValue = score.currentValue;
                        //    }
                        res.json(messageUtil.composeSucceededMessage(req, null, replyId));
                        //});

                        if (input.uList != null && input.uList.length > 0) {

                        }
                        redisClient.del('question:reply:list:' + questionId);
                    }
                });
            }
        }
    });
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   end   */

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   start   */
exports.postReplyNew = function (req, res) {
    var token = req.params.token;

    userService.getUserGagOrNotService(token, function (err, results) {
        if (err) {
            logger.error("Failed to postReplyNew - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to postReplyNew - " + err.message));
        } else {
            var gagOrNot = results._doc.gagOrNot;
            if(gagOrNot) {
                logger.error("Failed to postReplyNew - " + gagOrNot);
                res.json(messageUtil.composeFailedMessage(req, "您被禁言了!" + ""));
            } else {
                logger.debug("Succeeded to postReplyNew! - " + gagOrNot);

                var questionId = req.params.questionId;
                var input = req.body;

                res.header("Access-Control-Allow-Origin", "*");

                toolUtil.uploadImageService(null, null, req, function (err, images) {
                    if (err) {
                        logger.error('postReplyNew - uploadImage - ' + err.message);
                        res.json(messageUtil.composeFailedMessage(req, '回复失败'));
                    } else {
                        var tempImages = new Array();
                        var k = 0;
                        for (var i = 0; i < images.length; i++) {
                            if (images[i] != null)
                                tempImages[k++] = {
                                    "imageURL": images[i]
                                }
                        }
                        input['images'] = tempImages;

                        questionService.postReplyNewService(token, questionId, input, function (err, result) {
                            if (err) {
                                logger.error('Exception happened when postActivityReply ...!' + err.message);
                                res.json(messageUtil.composeFailedMessage(req, err.message));
                            } else {
                                var replyId = {
                                    "_id": result[9].replies[result[9].replies.length - 1]._id
                                };
                                replyId.reply = result[9].replies[result[9].replies.length - 1];
                                replyId.replyCountStr = toolUtil.transformNumber(result[9].replies.length);

                                if (replyId.reply.replyTo == null) replyId.reply.replyTo = undefined;

                                res.header("Access-Control-Allow-Origin", "*");
                                if (result[0].createdBy + '' == token) {
                                    res.json(messageUtil.composeSucceededMessage(req, null, replyId));
                                } else {
                                    var action = result[9].replies.length == 1 ? 16 : (result[9].category == 'question' ? 7 : 4);

                                    toolUtil.hessianInvokeAddScore(token, action, null, function (score) {
                                        if (score != null && score.currentValue != null) {
                                            replyId.currentValue = score.currentValue;
                                            replyId.changeValue = score.changeValue;
                                        }
                                        res.json(messageUtil.composeSucceededMessage(req, null, replyId));
                                    });
                                }

                                var key = 'catch:q:all:' + result[0].community;
                                var categoryKey = 'catch:q:category:' + result[9].category + ':' + result[0].community;
                                redisClient.del(key);
                                redisClient.del(categoryKey);
                                redisClient.del('question:reply:list:' + questionId);


                                if (input.uList != null && typeof input.uList == 'string') {
                                    input.uList = [input.uList];
                                }

                                //@功能
                                if (input.uList != null && input.uList.length > 0 && input.replyDesc.indexOf(atFlag) != -1) {
                                    questionService.replyAtService(result[0], replyId._id, input.uList, 'question', token, input.replyDesc);
                                }


                                if (input.replyTo == null && input.replyDesc.indexOf(atFlag) == -1) {
                                    toolUtil.putMessageQAMQ({
                                        msgType: 'reply2reply',
                                        uid: token,
                                        questionId: result[0]._id + '',
                                        replyDesc: input.replyDesc,
                                        contentType: 'question'
                                    });
                                }


                                //敏感词过滤
                                toolUtil.filteringSensitiveWords(result[0]._id, replyId._id, input.replyDesc, 'question', function (err, replyDesc) {
                                    //推送
                                    toolUtil.putMessageQAMQ({
                                        msgType: 'reply',
                                        isExistAt: input.uList != null && input.uList.length > 0 ? 1 : 0,
                                        atUidList: input.uList,
                                        replyUid: token,
                                        topicId: result[0]._id + '',
                                        replyId: replyId._id + '',
                                        replyDesc: replyDesc,
                                        contentType: 'question',
                                        isAsk: input.replyTo == null ? 0 : 1,
                                        toReplyUid: input.replyTo
                                    });
                                });
                            }
                        })
                    }
                });
            }
        }
    });
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   end   */

exports.getCategoryQuestionCount = function (req, res) {
    var token = req.params.token;
    var category = req.params.category;

    questionService.getCategoryQuestionCountService(token, category, function (err, result) {
        if (err) {
            logger.error('getCategoryQuestionCountService' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
}

exports.getCommunityQuestionAndReplyCount = function (req, res) {
    var token = req.params.token;
    var tagId = req.params.tagId;
    questionService.getCommunityQuestionAndReplyCountService(token, tagId, function (err, result) {
            if (err) {
                logger.error(err.message);
                res.json(messageUtil.composeFailedMessage(req, err.message));
            } else {
                res.json(messageUtil.composeSucceededMessage(req, null, result));
            }
        }
    )
};

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   start   */
/**
 * 感谢回复
 */
// 感谢一下
exports.thankReply = function (req, res) {

    var token = req.params.token;

    userService.getUserGagOrNotService(token, function (err, results) {
        if (err) {
            logger.error("Failed to thankReply - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to thankReply - " + err.message));
        } else {
            var gagOrNot = results._doc.gagOrNot;
            if(gagOrNot) {
                logger.error("Failed to thankReply - " + gagOrNot);
                res.json(messageUtil.composeFailedMessage(req, "您被禁言了!" + ""));
            } else {
                logger.debug("Succeeded to thankReply! - " + gagOrNot);

                var questionId = req.params.questionId;
                var replyId = req.params.replyId;
                var replyBy = req.params.replyBy;

                questionService.thankReplyService(questionId, replyId, replyBy, token, function (err, result) {
                    if (err) {
                        logger.error(err.message);
                        res.json(messageUtil.composeFailedMessage(req, err.message, 4003));
                    } else {
                        res.json(messageUtil.composeSucceededMessage(req, '感谢成功', {replyId: replyId}, 4003));
                        redisClient.del('question:reply:list:' + questionId);

                        //统计用户数据
                        redisClient.HINCRBY(redisKey.getUserDataStatisticKey(replyBy), 'thankedReply', 1);

                        if (result.category == 'question')
                            toolUtil.putMessageUserExpMQ({userId: replyBy, type: 1});
                        toolUtil.hessianInvokeAddScore(replyBy, 15, null, function (score) {

                        });
                    }
                })
            }
        }
    });
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   end   */

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   start   */
/**
 * 上传回答图片
 */
exports.uploadReplyImages = function (req, res) {
    var token = req.params.token;

    userService.getUserGagOrNotService(token, function (err, results) {
        if (err) {
            logger.error("Failed to uploadReplyImages - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to uploadReplyImages - " + err.message));
        } else {
            var gagOrNot = results._doc.gagOrNot;
            if(gagOrNot) {
                logger.error("Failed to uploadReplyImages - " + gagOrNot);
                res.json(messageUtil.composeFailedMessage(req, "您被禁言了!" + ""));
            } else {
                logger.debug("Succeeded to uploadReplyImages! - " + gagOrNot);

                var questionId = req.params.questionId;
                var replyId = req.params.replyId;
                var objectName = 'Replies';

                toolUtil.uploadImageService(objectName, replyId, req, function (err, images) {
                    if (err) {
                        res.json(messageUtil.composeFailedMessage(req, 'Failed to upload reply Images... - ' + err.message));
                    } else {
                        var tempImages = new Array();
                        var k = 0;
                        for (i = 0; i < images.length; i++) {
                            if (images[i] != null)
                                tempImages[k++] = {
                                    "imageURL": images[i]
                                }
                        }
                        questionService.setImagesToReply(questionId, replyId, tempImages, function (err, result) {
                            if (err || tempImages == null) {
                                res.json(messageUtil.composeFailedMessage(req, 'Failed to upload reply Images... - ' + err.message));
                            } else {
                                res.json(messageUtil.composeSucceededMessage(req, null, null));
                            }
                        });
                    }
                })
            }
        }
    });
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   end   */

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   start   */
/**
 * 修改回答
 */
exports.updateReply = function (req, res) {
    var token = req.params.token;

    userService.getUserGagOrNotService(token, function (err, results) {
        if (err) {
            logger.error("Failed to updateReply - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to updateReply - " + err.message));
        } else {
            var gagOrNot = results._doc.gagOrNot;
            if(gagOrNot) {
                logger.error("Failed to updateReply - " + gagOrNot);
                res.json(messageUtil.composeFailedMessage(req, "您被禁言了!" + ""));
            } else {
                logger.debug("Succeeded to updateReply! - " + gagOrNot);

                var questionId = req.params.questionId;
                var replyId = req.params.replyId;
                var input = req.body;

                logger.debug('Updating a reply: ' + 'questionId=' + questionId + '-----replyId=' + replyId);

                questionService.updateReplyService(questionId, replyId, input, function (err, result) {
                    if (err) {
                        logger.error('Exception happened when trying to update the reply data...!' + err.message);
                        res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to update the reply data...!'));
                    } else {
                        res.json(messageUtil.composeSucceededMessage(req, null, null));
                    }
                });
            }
        }
    });
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   end   */

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   start   */
/**
 * 删除回答
 */
// 删除回复
exports.deleteReply = function (req, res) {

    var token = req.params.token;

    userService.getUserGagOrNotService(token, function (err, results) {
        if (err) {
            logger.error("Failed to deleteReply - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to deleteReply - " + err.message));
        } else {
            var gagOrNot = results._doc.gagOrNot;
            if(gagOrNot) {
                logger.error("Failed to deleteReply - " + gagOrNot);
                res.json(messageUtil.composeFailedMessage(req, "您被禁言了!" + ""));
            } else {
                logger.debug("Succeeded to deleteReply! - " + gagOrNot);

                var questionId = req.params.questionId;
                var replyId = req.params.replyId;
                logger.debug('Deleting a reply: ' + 'questionId=' + questionId + '-----replyId=' + replyId);

                questionService.deleteReplyService(token, questionId, replyId, function (err, result) {
                    if (err) {
                        logger.error('Exception happened when trying to delete the reply data...!' + err.message);
                        res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to delete the reply data...!', 4004));
                    } else {
                        var data = {
                            replyCountStr: toolUtil.transformNumber(result[1].replies.length)
                        };
                        res.json(messageUtil.composeSucceededMessage(req, null, data, 4004));
                        redisClient.del('question:reply:list:' + questionId);

                        if (token != result[1].createdBy + '')
                            toolUtil.hessianInvokeAddScore(token, 29, null, function (value) {
                            });
                        //统计用户数据
                        redisClient.HINCRBY(redisKey.getUserDataStatisticKey(token), 'questionReply', -1);
                        /*  宝宝树66小区二次改造    add   chenf  20170823   start   */
                        toolUtil.changeUserStatisticsNew(token,'questionReply', -1);
                        /*  宝宝树66小区二次改造    add   chenf  20170823   end   */
                    }
                });
            }
        }
    });
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   end   */

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   start   */
/**
 * 删除回答图片
 */
exports.deleteReplyImages = function (req, res) {
    var token = req.params.token;

    userService.getUserGagOrNotService(token, function (err, results) {
        if (err) {
            logger.error("Failed to deleteReplyImages - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to deleteReplyImages - " + err.message));
        } else {
            var gagOrNot = results._doc.gagOrNot;
            if(gagOrNot) {
                logger.error("Failed to deleteReplyImages - " + gagOrNot);
                res.json(messageUtil.composeFailedMessage(req, "您被禁言了!" + ""));
            } else {
                logger.debug("Succeeded to deleteReplyImages! - " + gagOrNot);

                var questionId = req.params.questionId;
                var replyId = req.params.replyId;
                var images = req.body;
                logger.debug('Deleting a reply images: ' + replyId);

                questionService.deleteReplyImagesService(questionId, replyId, images, function (err, result) {
                    if (err) {
                        logger.error('Exception happened when trying to delete the reply images ...!' + err.message);
                        res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to delete the reply images...!'));
                    } else {
                        res.json(messageUtil.composeSucceededMessage(req, null, null));
                    }
                });
            }
        }
    });
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   end   */

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   start   */
/**
 * 采纳回答
 */
// 采纳一下
exports.adoptReply = function (req, res) {

    var token = req.params.token;
    userService.getUserGagOrNotService(token, function (err, results) {
        if (err) {
            logger.error("Failed to adoptReply - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to adoptReply - " + err.message));
        } else {
            var gagOrNot = results._doc.gagOrNot;
            if(gagOrNot) {
                logger.error("Failed to adoptReply - " + gagOrNot);
                res.json(messageUtil.composeFailedMessage(req, "您被禁言了!" + ""));
            } else {
                logger.debug("Succeeded to adoptReply! - " + gagOrNot);


                var questionId = req.params.questionId;
                var replyId = req.params.replyId;

                questionService.adoptReplyService(token, questionId, replyId, function (err, result) {
                    if (err) {
                        logger.error('Exception happened when trying to adopting a reply...!' + err.message);
                        res.json(messageUtil.composeFailedMessage(req, err.message, 4005));
                    } else {

                        res.json(messageUtil.composeSucceededMessage(req, null, {replyId: replyId}, 4005));
                        redisClient.del('question:reply:list:' + questionId);

                        if (result.category == 'question')
                            toolUtil.putMessageUserExpMQ({userId: result.replyBy, type: 2});


                        //统计用户数据
                        redisClient.HINCRBY(redisKey.getUserDataStatisticKey(result.replyBy), 'adoptedReply', 1);
                        toolUtil.changeUserStatistics(result.replyBy, result.replyCommunity, 'adoptedReply', 1);

                        toolUtil.hessianInvokeAddScore(result.replyBy, 5, null, function (score) {
                            if (result.score != null && result.score != 0) {
                                toolUtil.hessianManualAddScore(result.replyBy, 21, result.score, '获得悬赏', function (value) {
                                })
                            }
                        });

                        toolUtil.hessianInvokeAddScore(token, 24, null, function (value) {
                        });
                    }
                });
            }
        }
    });
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   end   */

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   start   */
/**
 * 创建投票
 */
exports.createPoll = function (req, res) {
    var token = req.params.token;
    userService.getUserGagOrNotService(token, function (err, results) {
        if (err) {
            logger.error("Failed to createPoll - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to createPoll - " + err.message));
        } else {
            var gagOrNot = results._doc.gagOrNot;
            if(gagOrNot) {
                logger.error("Failed to createPoll - " + gagOrNot);
                res.json(messageUtil.composeFailedMessage(req, "您被禁言了!" + ""));
            } else {
                logger.debug("Succeeded to createPoll! - " + gagOrNot);

                var questionId = {
                    "_id": result._id
                };
                res.json(messageUtil.composeSucceededMessage(req, null, questionId));
            }
        }
    });
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   end   */

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   start   */
/**
 * 上传投票图片
 */
exports.uploadPollImages = function (req, res) {
    var token = req.params.token;

    userService.getUserGagOrNotService(token, function (err, results) {
        if (err) {
            logger.error("Failed to uploadPollImages - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to uploadPollImages - " + err.message));
        } else {
            var gagOrNot = results._doc.gagOrNot;
            if(gagOrNot) {
                logger.error("Failed to uploadPollImages - " + gagOrNot);
                res.json(messageUtil.composeFailedMessage(req, "您被禁言了!" + ""));
            } else {
                logger.debug("Succeeded to uploadPollImages! - " + gagOrNot);


                var objectName = 'Poll';
                var pollId = req.params.pollId;
                toolUtil.uploadImageService(objectName, pollId, req, function (err, images) {
                    if (err) {
                        res.json(messageUtil.composeFailedMessage(req, 'Failed to upload poll Images... - ' + err.message));
                    } else {
                        var tempImages = new Array();
                        var k = 0;
                        for (i = 0; i < images.length; i++) {
                            if (images[i] != null)
                                tempImages[k++] = {
                                    "imageURL": images[i]
                                }
                        }
                        questionService.setImagesToQuestion(pollId, tempImages, function (err, result) {
                            if (err || tempImages == null) {
                                res.json(messageUtil.composeFailedMessage(req, 'Failed to upload poll Images... - ' + err.message));
                            } else {
                                res.json(messageUtil.composeSucceededMessage(req, null, null));
                            }
                        });
                    }
                })
            }
        }
    });
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   end   */

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   start   */
/**
 * 修改投票
 */
exports.updatePoll = function (req, res) {
    var token = req.params.token;

    userService.getUserGagOrNotService(token, function (err, results) {
        if (err) {
            logger.error("Failed to updatePoll - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to updatePoll - " + err.message));
        } else {
            var gagOrNot = results._doc.gagOrNot;
            if(gagOrNot) {
                logger.error("Failed to updatePoll - " + gagOrNot);
                res.json(messageUtil.composeFailedMessage(req, "您被禁言了!" + ""));
            } else {
                logger.debug("Succeeded to updatePoll! - " + gagOrNot);

                var pollId = req.params.pollId;
                var input = req.body;

                logger.debug('Updating a Poll: ' + pollId);

                questionService.updatePollService(pollId, input, function (err, result) {
                    if (err) {
                        logger.error('Exception happened when trying to update the Poll data...!');
                        res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to update the Poll data...!'));
                    } else {
                        res.json(messageUtil.composeSucceededMessage(req, null, null));
                    }
                });
            }
        }
    });
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   end   */

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   start   */
/**
 * 删除投票
 */
exports.deletePoll = function (req, res) {
    var token = req.params.token;

    userService.getUserGagOrNotService(token, function (err, results) {
        if (err) {
            logger.error("Failed to deletePoll - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to deletePoll - " + err.message));
        } else {
            var gagOrNot = results._doc.gagOrNot;
            if(gagOrNot) {
                logger.error("Failed to deletePoll - " + gagOrNot);
                res.json(messageUtil.composeFailedMessage(req, "您被禁言了!" + ""));
            } else {
                logger.debug("Succeeded to deletePoll! - " + gagOrNot);


                var pollId = req.params.pollId;
                logger.debug('Deleting a Poll: ' + pollId);

                questionService.deleteQuestionService(pollId, function (err, result) {
                    if (err) {
                        logger.error('Exception happened when trying to delete the poll ...!');
                        res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to delete the poll...!'));
                    } else {
                        res.json(messageUtil.composeSucceededMessage(req, null, null));
                    }
                })
            }
        }
    });
}
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   end   */

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   start   */
/**
 * 删除投票图片
 */
exports.deletePollImage = function (req, res) {

    var token = req.params.token;

    userService.getUserGagOrNotService(token, function (err, results) {
        if (err) {
            logger.error("Failed to deletePollImage - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to deletePollImage- " + err.message));
        } else {
            var gagOrNot = results._doc.gagOrNot;
            if(gagOrNot) {
                logger.error("Failed to deletePollImage - " + gagOrNot);
                res.json(messageUtil.composeFailedMessage(req, "您被禁言了!" + ""));
            } else {
                logger.debug("Succeeded to deletePollImage! - " + gagOrNot);

                var pollId = req.params.pollId;
                var images = req.body;
                logger.debug('Deleting a Poll images: ' + pollId);

                questionService.deleteQuestionImagesService(pollId, images, function (err, result) {
                    if (err) {
                        logger.error('Exception happened when trying to delete the poll images ...!');
                        res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to delete the poll images...!'));
                    } else {
                        res.json(messageUtil.composeSucceededMessage(req, null, null));
                    }
                })
            }
        }
    });
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   end   */

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   start   */
/**
 * 投票
 */
exports.doPoll = function (req, res) {

    var token = req.params.token;

    userService.getUserGagOrNotService(token, function (err, results) {
        if (err) {
            logger.error("Failed to doPoll - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to doPoll - " + err.message));
        } else {
            var gagOrNot = results._doc.gagOrNot;
            if(gagOrNot) {
                logger.error("Failed to doPoll - " + gagOrNot);
                res.json(messageUtil.composeFailedMessage(req, "您被禁言了!" + ""));
            } else {
                logger.debug("Succeeded to doPoll! - " + gagOrNot);

                var pollId = req.params.pollId;
                var input = req.body;

                questionService.doPollService(pollId, input, token, function (err, result) {
                    if (err) {
                        logger.error('Exception happened when trying to poll ...!' + err.message);
                        res.json(messageUtil.composeFailedMessage(req, err.message));
                    } else {
                        res.json(messageUtil.composeSucceededMessage(req, null, result));
                    }
                })
            }
        }
    });
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   end   */

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   start   */
/**
 * 关闭投票
 */
exports.closePoll = function (req, res) {
    var token = req.params.token;

    userService.getUserGagOrNotService(token, function (err, results) {
        if (err) {
            logger.error("Failed to closePoll - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to closePoll - " + err.message));
        } else {
            var gagOrNot = results._doc.gagOrNot;
            if(gagOrNot) {
                logger.error("Failed to closePoll - " + gagOrNot);
                res.json(messageUtil.composeFailedMessage(req, "您被禁言了!" + ""));
            } else {
                logger.debug("Succeeded to closePoll! - " + gagOrNot);

                var pollId = req.params.pollId;

                questionService.closePollService(pollId, function (err, result) {
                    if (err) {
                        logger.error('Exception happened when close a poll ...!' + pollId);
                        res.json(messageUtil.composeFailedMessage(req, 'Exception happened when close a poll...!'));
                    } else {
                        res.json(messageUtil.composeSucceededMessage(req, null, null));
                    }
                })
            }
        }
    });
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   end   */

/**
 * 获取我的提问列表
 * @param req
 * @param res
 */
exports.getMyQuestionAndPollList = function (req, res) {
    var token = req.params.token;
    var page = req.params.pageNo;

    questionService.getMyQuestionAndPollListService(page, token, function (err, results) {
        if (err) {
            logger.error('Exception happened when get QuestionAndPollList ...!' + token);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when get QuestionAndPollList...!'));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    });
};

exports.getMyQuestionList = function (req, res) {
    var token = req.params.token;
    var page = req.params.pageNo;

    questionService.getMyQuestionListService(page, token, function (err, results) {
        if (err) {
            logger.error('Exception happened when get getMyQuestionList ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    })
};

exports.getMyReplyList = function (req, res) {
    var token = req.params.token;
    var page = req.params.pageNo;

    questionService.getMyReplyListService(page, token, function (err, results) {
        if (err) {
            logger.error('Exception happened when get getMyReplyList ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    })
};

/**
 * 获取我所回复的提问列表
 * @param req
 * @param res
 */
exports.getMyRepliedQuestionList = function (req, res) {
    var token = req.params.token;
    var page = req.params.pageNo;

    questionService.getMyRepliedQuestionListService(page, token, function (err, results) {
        if (err) {
            logger.error('Exception happened when get QuestionAndPollList ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when get QuestionAndPollList...!'));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    });
};

/**
 * 获取问题详情
 * @param req
 * @param res
 */
exports.getDetailOfQuestionOrPoll = function (req, res) {
    var questionOrPollId = req.params.questionOrPollId;
    var token = req.params.token;

    questionService.getDetailOfQuestionOrPollService(token, questionOrPollId, function (err, result) {
        if (err) {
            logger.error('Exception happened when get a QuestionAndPoll ...!' + questionOrPollId + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};

exports.getDetailOfQuestion = function (req, res) {
    var questionOrPollId = req.params.questionId;
    var token = req.params.token;
    var clickSource = req.cparams.clickSource;
    var vCode = req.cparams.vcode;

    questionService.getDetailOfQuestionService(token, questionOrPollId, vCode, function (err, result) {
        if (err) {
            logger.error('Exception happened when getDetailOfQuestion ...!' + questionOrPollId + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 4006));
        } else {

            if (Number(vCode) >= 200000 && (result.category == 'question' || result.category == 'lostAndFound')) {
                //result._doc.praiseUsers = [];
            }

            res.json(messageUtil.composeSucceededMessage(req, null, result, 4006));

            toolUtil.putMessageSmartRankMQ({questionId: questionOrPollId, type: 5});

            if (clickSource != null) {
                var message = {
                    userId: token,
                    contentId: questionOrPollId,
                    type: 1,
                    clickSource: clickSource,
                    typeDesc: '话题',
                    deviceId: req.params.deviceId,
                    vname: req.query.vname,
                    vcode: req.query.vcode,
                    os: req.query.type,
                    createTime: new Date().getTime()
                }
                toolUtil.putMessageLogMQ(message);
            }
        }
    })
};

exports.getQuestionPartDetail = function (req, res) {
    var questionId = req.params.questionId;
    var token = req.params.token;
    var clickSource = req.query.clickSource;
    var vCode = req.query.vcode;

    var lang = req.cparams.lang;

    questionService.getQuestionPartDetailService(token, questionId, function (err, result) {
        if (err) {
            logger.error('Exception happened when getQuestionPartDetail ...!' + questionId + err.message);

            if (lang && err['message_' + lang])
                res.json(messageUtil.composeFailedMessage(req, err['message_' + lang], 4006));
            else
                res.json(messageUtil.composeFailedMessage(req, err.message, 4006));
        } else {

            if (Number(vCode) >= 200000 && (result.category == 'question' || result.category == 'lostAndFound')) {
                //result.praiseUsers = [];
            }

            res.json(messageUtil.composeSucceededMessage(req, null, result, 4006));
            toolUtil.putMessageSmartRankMQ({questionId: questionId, type: 5});

            if (clickSource != null) {
                var message = {
                    userId: token,
                    contentId: questionId,
                    type: 1,
                    clickSource: clickSource,
                    typeDesc: '话题',
                    vname: req.query.vname,
                    vcode: req.query.vcode,
                    os: req.query.type,
                    deviceId: req.params.deviceId,
                    createTime: new Date().getTime()
                };
                toolUtil.putMessageLogMQ(message);
            }
        }
    })
};

exports.getDetailReplyOfQuestion = function (req, res) {
    var page = req.params.page;
    var token = req.params.token;
    var questionId = req.params.questionId;
    var vcode = req.cparams.vcode;

    var key = 'question:reply:list:' + questionId;
    var mark = "";
    if (vcode < 1500) {
        mark = "old";
    } else {
        mark = "new";
    }

    redisClient.HGET(key, mark + ":" + page + ':' + vcode, function (err, value) {
        if (value != null) {
            logger.info('get getDetailReplyOfQuestion from catch');
            res.json(messageUtil.composeSucceededMessage(req, null, JSON.parse(value), 4007))
        } else {
            logger.info('get getDetailReplyOfQuestion from mongo');

            questionService.getDetailReplyOfQuestionService(page, token, questionId, vcode, function (err, results) {
                if (err) {
                    logger.error('Exception happened when getDetailReplyOfQuestion ...!' + questionId + err.message);
                    res.json(messageUtil.composeFailedMessage(req, err.message, 4007));
                } else {
                    res.json(messageUtil.composeSucceededMessage(req, null, results, 4007));
                    redisClient.HSET(key, mark + ":" + page + ':' + vcode, JSON.stringify(results));
                    redisClient.EXPIRE(key, 300);
                }
            });
        }
    });


};

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   start   */
exports.praiseReplyService = function (req, res) {
    var token = req.params.token;

    userService.getUserGagOrNotService(token, function (err, results) {
        if (err) {
            logger.error("Failed to praiseReplyService - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to praiseReplyService - " + err.message));
        } else {
            var gagOrNot = results._doc.gagOrNot;
            if(gagOrNot) {
                logger.error("Failed to praiseReplyService - " + gagOrNot);
                res.json(messageUtil.composeFailedMessage(req, "您被禁言了!" + ""));
            } else {
                logger.debug("Succeeded to praiseReplyService! - " + gagOrNot);

                var replyId = req.params.replyId;
                var replyBy = req.params.replyBy;

                questionService.praiseReplyService(replyId, replyBy, token, function (err, result) {
                    if (err) {
                        logger.error('Exception happened when praise a reply ...!' + err.message);
                        res.json(messageUtil.composeFailedMessage(req, err.message, 4008));
                    } else {
                        res.json(messageUtil.composeSucceededMessage(req, null, {replyId: replyId}, 4008));
                    }
                })
            }
        }
    });
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   end   */

/**
 * 获取专题详情
 * @param req
 * @param res
 */

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   start   */
/**
 * 问题置顶
 */
exports.moveQuestionToTop = function (req, res) {
    var token = req.params.token;

    userService.getUserGagOrNotService(token, function (err, results) {
        if (err) {
            logger.error("Failed to moveQuestionToTop - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to moveQuestionToTop - " + err.message));
        } else {
            var gagOrNot = results._doc.gagOrNot;
            if(gagOrNot) {
                logger.error("Failed to moveQuestionToTop - " + gagOrNot);
                res.json(messageUtil.composeFailedMessage(req, "您被禁言了!" + ""));
            } else {
                logger.debug("Succeeded to moveQuestionToTop! - " + gagOrNot);
                questionService.moveQuestionToTopService(opt, function (err, result) {
                    if (err) {
                        logger.error('Exception happened when move question or poll to top ...!' + err.message);
                        res.json(messageUtil.composeFailedMessage(req, 'Exception happened when move question or poll to top...!' + err.message));
                    } else {
                        res.json(messageUtil.composeSucceededMessage(req, null, null));
                    }
                })


                var opt = req.body;

            }
        }
    });
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   end   */

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   start   */
/**
 * 取消置顶
 */
exports.cancelTopQuestion = function (req, res) {

    var token = req.params.token;

    userService.getUserGagOrNotService(token, function (err, results) {
        if (err) {
            logger.error("Failed to cancelTopQuestion - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to cancelTopQuestion - " + err.message));
        } else {
            var gagOrNot = results._doc.gagOrNot;
            if(gagOrNot) {
                logger.error("Failed to cancelTopQuestion - " + gagOrNot);
                res.json(messageUtil.composeFailedMessage(req, "您被禁言了!" + ""));
            } else {
                logger.debug("Succeeded to cancelTopQuestion! - " + gagOrNot);

                var input = req.body;

                questionService.cancelTopQuestionService(input, function (err, result) {
                    if (err) {
                        logger.error('Exception happened when cancelTopQuestion ...!' + err.message);
                        res.json(messageUtil.composeFailedMessage(req, 'Exception happened when cancelTopQuestion...!' + err.message));
                    } else {
                        res.json(messageUtil.composeSucceededMessage(req, null, null));
                    }
                });
            }
        }
    });
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   end   */

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   start   */
/**
 * 回复置顶
 */
exports.moveReplyToTop = function (req, res) {

    var token = req.params.token;

    userService.getUserGagOrNotService(token, function (err, results) {
        if (err) {
            logger.error("Failed to moveReplyToTop - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to moveReplyToTop - " + err.message));
        } else {
            var gagOrNot = results._doc.gagOrNot;
            if(gagOrNot) {
                logger.error("Failed to moveReplyToTop - " + gagOrNot);
                res.json(messageUtil.composeFailedMessage(req, "您被禁言了!" + ""));
            } else {
                logger.debug("Succeeded to moveReplyToTop! - " + gagOrNot);


                var questionId = req.params.questionId;
                var replyId = req.params.replyId;

                questionService.moveReplyToTopService(questionId, replyId, function (err, result) {
                    if (err) {
                        logger.error('Exception happened when move reply to top ...!' + err.message);
                        res.json(messageUtil.composeFailedMessage(req, 'Exception happened when move reply to top...!' + err.message));
                    } else {
                        res.json(messageUtil.composeSucceededMessage(req, null, null));
                    }
                })
            }
        }
    });
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   end   */

/**
 *  获取推荐给我的问题和投票列表
 */
exports.getRecommendedQuestionAndPollList = function (req, res) {
    var token = req.params.token;

    questionService.getRecommendedQuestionAndPollListService(token, function (err, result) {
        if (err) {
            logger.error('Exception happened when get recommended question and poll list ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when get recommended question and poll list...!' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};

/**
 * 获取小区所有问题列表
 */
exports.getAllCommunityQuestionList = function (req, res) {
    var token = req.params.token;
    var page = req.params.pageNo;

    questionService.getAllCommunityQuestionListService(page, token, function (err, result) {
        if (err) {
            logger.error('Exception happened when get all question list ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when get all question list...!' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};

exports.getAllCommunityQuestionListNew = function (req, res) {
    var token = req.params.token;
    var ts = req.params.ts;
    var sortName = 'dateLastModified';

    if (req.cparams != null) {
        if (req.cparams.sortrule == 'release')
            sortName = 'dateCreated';
        if (req.cparams.level != null)
            var level = Number(req.cparams.level);

        var range = req.cparams.range;
    }

    var vCode = req.cparams.vcode;


    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            res.json(messageUtil.composeFailedMessage(req, err.message, 4009));
        } else {
            var key = 'catch:q:all:' + user.community._id;

            redisClient.HGET(key, sortName + ':' + ts + ':' + vCode, function (err, value) {
                if (value != null && level == null && range == null) {
                    logger.info('get all question from catch');
                    res.json(messageUtil.composeSucceededMessage(req, null, JSON.parse(value), 4009))
                } else {
                    questionService.getAllCommunityQuestionListNewService(ts, token, sortName, level, range, vCode, function (err, result) {
                        if (err) {
                            logger.error('Exception happened when getAllCommunityQuestionListNew ...!' + err.message);
                            res.json(messageUtil.composeFailedMessage(req, err.message, 4009));
                        } else {
                            var list = result.list;
                            var data = {
                                ts: list.length > 0 ? list[list.length - 1][sortName].getTime() : (new Date("2000/04/01 00:00:00")).getTime(),
                                all: list
                            };
                            res.json(messageUtil.composeSucceededMessage(req, null, data, 4009));

                            //redis缓存
                            if (level == null && range == null) {
                                redisClient.HSET(key, sortName + ':' + ts + ':' + vCode, JSON.stringify(data));
                                redisClient.EXPIRE(key, 300);
                            }
                        }
                    })
                }
            });
        }
    });
};

exports.getQuestionListByTag = function (req, res) {
    var token = req.params.token;
    var ts = req.params.ts;
    var tagId = req.params.tagId;
    var vCode = req.cparams.vcode;

    questionService.getQuestionListByTagService(ts, tagId, token, vCode, function (err, result) {
        if (err) {
            logger.error('Exception happened when getQuestionListByTag ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 4010));
        } else {
            var data = {
                ts: result.length > 0 ? result[result.length - 1].dateLastModified.getTime() : (new Date("2000/04/01 00:00:00")).getTime(),
                tagList: result
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data, 4010));
        }
    })
};

/**
 * 获取小区所有投票
 */
exports.getAllCommunityPollList = function (req, res) {
    var token = req.params.token;
    var page = req.params.pageNo;

    questionService.getAllCommunityPollListService(page, token, function (err, result) {
        if (err) {
            logger.error('Exception happened when get all poll list ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when get all poll list...!' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};

/**
 * 获取小区专题列表
 */
exports.getAllCommunitySpecialTopicList = function (req, res) {
    var token = req.params.token;
    var page = req.params.pageNo;

    questionService.getAllCommunitySpecialTopicListService(page, token, function (err, result) {
        if (err) {
            logger.error('Exception happened when get all SpecialTopic list ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when get all SpecialTopic list...!' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};


/**
 * 根据分类获取问题和投票列表
 */
exports.getCategorizedQuestionAndPollList = function (req, res) {
    var tagId = req.params.tagId;
    var token = req.params.token;
    var page = req.params.pageNo;

    questionService.getCategorizedQuestionAndPollListService(page, tagId, token, function (err, result) {
        if (err) {
            logger.error('Exception happened when get categorized question and poll list ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when get categorized question and poll list...!' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};

/**
 * 搜索列表
 * @param req
 * @param res
 */
exports.searchQuestionAndPollList = function (req, res) {
    var token = req.params.token;
    var keyword = req.params.keyword;

    questionService.searchQuestionAndPollListService(keyword, token, function (err, result) {
        if (err) {
            logger.error('Exception happened when search question and poll list ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
}

/**
 * 获取专家回答的问题
 */
exports.getExpertRepliedQuestionList = function (req, res) {
    var token = req.params.token;
    var page = req.params.pageNo;

    questionService.getExpertRepliedQuestionListService(page, token, function (err, result) {
        if (err) {
            logger.error('Exception happened when get expert question and poll list ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when get expert question and poll list...!' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};

/**
 * 获取最新问题
 */
exports.getLatestQuestionList = function (req, res) {
    var token = req.params.token;
    var page = req.params.pageNo;
    questionService.getLatestQuestionListService(page, token, function (err, results) {
        if (err) {
            logger.error('Exception happened when get community latest question list ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when get community latest question list...!' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    })
};

/**
 * 获取达人排行榜
 */
exports.getTalentList = function (req, res) {
    var token = req.params.token;
    var tagId = req.params.tagId;

    questionService.getTalentListService(tagId, token, function (err, results) {
        if (err) {
            logger.error('Exception happened when get talent list ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when get talent list...!' + err.message, 4011));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results, 4011));
        }
    })
};

//===============================新版求助=========================
exports.getCategoryQuestionList = function (req, res) {
    var token = req.params.token;
    var category = req.params.category;
    var page = req.params.pageNo;

    questionService.getCategoryQuestionListService(token, category, page, function (err, results) {
        if (err) {
            logger.error('Exception happened when getCategoryQuestionList ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when getCategoryQuestionList...!' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    })
};

exports.getCategoryQuestionListNew = function (req, res) {
    var token = req.params.token;
    var category = req.params.category;
    var ts = req.params.ts;
    var vCode = req.cparams.vcode;

    var sortName = 'dateLastModified';
    if (req.cparams != null) {
        var sortrule = req.cparams.sortrule;
        if (sortrule == 'release') {
            sortName = 'dateCreated'
        }

        var range = req.cparams.range;
    }

    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            res.json(messageUtil.composeFailedMessage(req, err.message, 4012));
        } else {
            var key = 'catch:q:category:' + category + ':' + user.community._id;

            redisClient.HGET(key, sortName + ':' + ts + ':' + vCode, function (err, value) {
                if (value != null && range == null) {
                    logger.info('get category question from catch');
                    res.json(messageUtil.composeSucceededMessage(req, null, JSON.parse(value), 4012))
                } else {
                    logger.info('get category question from mongo');
                    questionService.getCategoryQuestionListNewService(token, category, ts, sortName, vCode, range, function (err, result) {
                            if (err) {
                                logger.error('Exception happened when getCategoryQuestionListNew ...!' + err.message);
                                res.json(messageUtil.composeFailedMessage(req, err.message, 4012));
                            } else {

                                var data = {
                                    ts: result.length > 0 ? result[result.length - 1][sortName].getTime() : new Date("2000/04/01 00:00:00").getTime(),
                                    categoryList: result
                                };
                                res.json(messageUtil.composeSucceededMessage(req, null, data, 4012));
                                if (range == null) {
                                    redisClient.HSET(key, sortName + ':' + ts + ':' + vCode, JSON.stringify(data));
                                    redisClient.EXPIRE(key, 300);
                                }
                            }
                        }
                    )
                }
            });
        }
    });
}


//====================================Web端===============================

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   start   */
/**
 * question-controller.js
 * 创建问题
 * author:chenjinzhuan
 */
exports.createQuestion = function (req, res) {

    var token = req.params.token;

    userService.getUserGagOrNotService(token, function (err, results) {
        if (err) {
            logger.error("Failed to createQuestion - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to createQuestion - " + err.message));
        } else {
            var gagOrNot = results._doc.gagOrNot;
            if(gagOrNot) {
                logger.error("Failed to createQuestion - " + gagOrNot);
                res.json(messageUtil.composeFailedMessage(req, "您被禁言了!" + ""));
            } else {
                logger.debug("Succeeded to createQuestion! - " + gagOrNot);

                var input = req.body;
                questionService.createQuestionService(input, function (err, result) {
                    if (err) {
                        logger.error("Failed to create RESTFull service - " + err.message);
                        res.json(messageUtil.composeFailedMessage(req, "Failed to post question - " + err.message));
                    } else {
                        logger.debug("Succeeded to create RESTFull service! - " + result._id);
                        res.json(messageUtil.composeSucceededMessage(req, null, result._id));
                    }
                });
            }
        }
    });
}
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   end   */

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   start   */
/**
 * question-controller.js
 * 更新问题
 * author:chenjinzhuan
 */
exports.backOfficeUpdateQuestion = function (req, res) {

    var token = req.params.token;

    userService.getUserGagOrNotService(token, function (err, results) {
        if (err) {
            logger.error("Failed to backOfficeUpdateQuestion - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to backOfficeUpdateQuestion - " + err.message));
        } else {
            var gagOrNot = results._doc.gagOrNot;
            if(gagOrNot) {
                logger.error("Failed to backOfficeUpdateQuestion - " + gagOrNot);
                res.json(messageUtil.composeFailedMessage(req, "您被禁言了!" + ""));
            } else {
                logger.debug("Succeeded to backOfficeUpdateQuestion! - " + gagOrNot);

                var id = req.params.objId;
                var input = req.body;

                questionService.updateOneQuestionService(id, input, function (err, results) {
                    if (err) {
                        logger.error('Exception happened when trying to update the Question data...!' + err.message);
                        res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to update the Question  data...!'));
                    } else {
                        if (results != 0) {
                            logger.debug("Update Question  successfully...!");
                            res.json(messageUtil.composeSucceededMessage(req, null, null));

                            if (input.tag != null) {
                                toolUtil.putMessageQAMQ({
                                    msgType: 'hobby',
                                    questionId: id + '',
                                    contentType: 'question'
                                });
                            }

                        } else {
                            logger.error('Failed to update the Question , it is not existing! -' + id);
                            res.json(messageUtil.composeFailedMessage(req, 'Failed to update the Question , it is not existing! -' + id));
                        }
                    }
                })
            }
        }
    });
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   end   */

/**
 * question-controller.js
 * 获取问题列表
 * author:chenjinzhuan
 */
exports.getQuestionList = function (req, res) {

    questionService.getQuestionListService(function (err, results) {
        if (err) {
            logger.error('Exception happened when get Question List ...!');
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when get Question List...!'));
        } else {
            logger.debug("get Question List  successfully...!");
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    });

};

/**
 * question-controller.js
 * 根据条件查找问题列表
 * author:chenjinzhuan
 */
exports.searchQuestion = function (req, res) {

    var question = req.body;
    logger.debug('question:' + question);

    questionService.searchQuestionService(question, function (err, results) {
        if (err) {
            logger.error('Exception happened when search Question...!');
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when search Question...!'));
        } else {
            logger.debug("search Question successfully...!");
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    });

};

/**
 * question-controller.js
 * 通过Id获取问题
 * author:chenjinzhuan
 */
exports.getQuestionById = function (req, res) {
    var id = req.params.objId;
    questionService.getQuestionByIdService(id, function (err, results) {
        if (err) {
            logger.error('Exception happened when get question by Id ...!');
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when get question by Id...!'));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    });

};

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   start   */
// 删除一个帖子
exports.deleteOneQuestion = function (req, res) {

    // 由于opm-v2也要调取这个接口，禁言功能暂时取消
   /* var token = req.params.token;

    userService.getUserGagOrNotService(token, function (err, results) {
        if (err) {
            logger.error("Failed to deleteOneQuestion - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to deleteOneQuestion - " + err.message));
        } else {
            var gagOrNot = results._doc.gagOrNot;
            if(gagOrNot) {
                logger.error("Failed to deleteOneQuestion - " + gagOrNot);
                res.json(messageUtil.composeFailedMessage(req, "您被禁言了!" + ""));
            } else {
                logger.debug("Succeeded to deleteOneQuestion! - " + gagOrNot);

                var questionId = req.params.questionId;

                questionService.deleteQuestionService(questionId, function (err, result) {
                    if (err) {
                        logger.error('Exception happened when trying to delete the question ...!' + err.message);
                        res.json(messageUtil.composeFailedMessage(req, err.message, 4002));
                    } else {
                        res.json(messageUtil.composeSucceededMessage(req, null, null, 4002));

                        //统计用户数据
                        toolUtil.changeUserStatistics(result[0].createdBy, result[0].community, 'question', -1);

                    }
                })
            }
        }
    });*/
    var questionId = req.params.questionId;

    questionService.deleteQuestionService(questionId, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying to delete the question ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 4002));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null, 4002));

            //统计用户数据
            toolUtil.changeUserStatistics(result[0].createdBy, result[0].community, 'question', -1);

        }
    })
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   end   */

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   start   */
/**
 * question-controller.js
 * 修改问题顺序
 * author:chenjinzhuan
 */
exports.changeQuestionOrder = function (req, res) {

    var token = req.params.token;

    userService.getUserGagOrNotService(token, function (err, results) {
        if (err) {
            logger.error("Failed to changeQuestionOrder - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to changeQuestionOrder - " + err.message));
        } else {
            var gagOrNot = results._doc.gagOrNot;
            if(gagOrNot) {
                logger.error("Failed to changeQuestionOrder - " + gagOrNot);
                res.json(messageUtil.composeFailedMessage(req, "您被禁言了!" + ""));
            } else {
                logger.debug("Succeeded to changeQuestionOrder! - " + gagOrNot);


                var question = req.body;
                questionService.changeQuestionOrderService(question, function (err, results) {
                    if (err) {
                        logger.error('Exception happened when trying to change question order...!');
                        res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to change question order...!'));
                    } else {
                        if (results != null) {
                            logger.debug("Change question order successfully...!");
                            res.json(messageUtil.composeSucceededMessage(req, null, null));
                        } else {
                            logger.error('Failed to change question order, it is not existing! -' + id);
                            res.json(messageUtil.composeFailedMessage(req, 'Failed to change question order, it is not existing! -'));
                        }
                    }
                })
            }
        }
    });
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   end   */


/**
 * question-controller.js
 * 获取问题列表
 * author:chenjinzhuan
 */
exports.getReplyList = function (req, res) {
    var questionId = req.params.questionOrPollId;
    //var token = req.params.token;

    questionService.getReplyListService(questionId, function (err, result) {
        if (err) {
            logger.error('Exception happened when get a QuestionAndPoll ...!' + questionOrPollId + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when get a QuestionAndPoll...!' + err.message));
        } else {
            //logger.debug(result.replies);
            res.json(messageUtil.composeSucceededMessage(req, null, result.replies));
        }
    })
};


/**
 * question-controller.js
 * 根据条件查找回复列表
 * author:chenjinzhuan
 */
exports.searchReply = function (req, res) {

    var input = req.body;
    logger.debug('input:' + input);

    questionService.searchReplyService(input, function (err, results) {
        if (err) {
            logger.error('Exception happened when search Question...!');
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when search Question...!'));
        } else {
            logger.debug("search Question successfully...!");
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    });

};

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   start   */
/**
 * question-controller.js
 * 删除回答
 * author:chenjinzhuan
 */
exports.deleteReplyByPost = function (req, res) {

    var token = req.params.token;

    userService.getUserGagOrNotService(token, function (err, results) {
        if (err) {
            logger.error("Failed to deleteReplyByPost - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to deleteReplyByPost - " + err.message));
        } else {
            var gagOrNot = results._doc.gagOrNot;
            if(gagOrNot) {
                logger.error("Failed to deleteReplyByPost - " + gagOrNot);
                res.json(messageUtil.composeFailedMessage(req, "您被禁言了!" + ""));
            } else {
                logger.debug("Succeeded to deleteReplyByPost! - " + gagOrNot);

                var input = req.body;
                var questionId = input.questionId;
                var replyId = input.replyId;

                logger.debug('Deleting a reply: ' + 'questionId=' + questionId + '-----replyId=' + replyId);

                questionService.deleteReplyService(questionId, replyId, function (err, result) {
                    if (err) {
                        logger.error('Exception happened when trying to delete the reply data...!' + err.message);
                        res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to delete the reply data...!'));
                    } else {
                        res.json(messageUtil.composeSucceededMessage(req, null, null));
                    }
                });
            }
        }
    });
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   end   */

exports.getNoReplyQuestionList = function (req, res) {
    var communityId = req.params.objId;


    questionService.getNoReplyQuestionListService(communityId, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying to getNoReplyQuestionList...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to getNoReplyQuestionList...!'));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   start   */
exports.backOfficePostReply = function (req, res) {

    var token = req.params.token;

    userService.getUserGagOrNotService(token, function (err, results) {
        if (err) {
            logger.error("Failed to backOfficePostReply - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to backOfficePostReply - " + err.message));
        } else {
            var gagOrNot = results._doc.gagOrNot;
            if(gagOrNot) {
                logger.error("Failed to backOfficePostReply - " + gagOrNot);
                res.json(messageUtil.composeFailedMessage(req, "您被禁言了!" + ""));
            } else {
                logger.debug("Succeeded to backOfficePostReply! - " + gagOrNot);

                var questionId = req.params.objId;
                var input = req.body;


                questionService.backOfficePostReplyService(questionId, input, function (err, result) {
                    if (err) {
                        logger.error('Exception happened when trying to delete the question images ...!' + err.message);
                        res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to delete the question images...!'));
                    } else {
                        res.json(messageUtil.composeSucceededMessage(req, null, null));
                    }
                });
            }
        }
    });
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   end   */

exports.getReportQuestion = function (req, res) {
    var communityId = req.params.communityId;

    questionService.getReportQuestionService(communityId, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying to getReportQuestion ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to getReportQuestion...!'));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   start   */
exports.deleteReportQuestion = function (req, res) {
    var token = req.params.token;

    userService.getUserGagOrNotService(token, function (err, results) {
        if (err) {
            logger.error("Failed to deleteReportQuestion - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to deleteReportQuestion - " + err.message));
        } else {
            var gagOrNot = results._doc.gagOrNot;
            if(gagOrNot) {
                logger.error("Failed to deleteReportQuestion - " + gagOrNot);
                res.json(messageUtil.composeFailedMessage(req, "您被禁言了!" + ""));
            } else {
                logger.debug("Succeeded to deleteReportQuestion! - " + gagOrNot);


                var questionId = req.params.questionId;

                questionService.deleteReportQuestionService(questionId, function (err, result) {
                    if (err) {
                        logger.error('Exception happened when trying to deleteReportQuestion ...!' + err.message);
                        res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to deleteReportQuestion...!'));
                    } else {
                        res.json(messageUtil.composeSucceededMessage(req, null, null));
                    }
                })
            }
        }
    });
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   end   */

exports.getRecommendQuestion = function (req, res) {
    var opt = req.body;
    var page = req.params.page;
    var size = req.params.size;

    //if (opt.tag == '有标签') {
    //    opt.tag = {$exists: true};
    //    opt.$where = "this.tag.length>0"
    //} else if (opt.tag == '无标签') {
    //    opt.tag = {$size: 0};
    //}

    questionService.getRecommendQuestionService(opt, page, size, function (err, results) {
        if (err) {
            logger.error('Exception happened when trying to getRecommendQuestion ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to getRecommendQuestion...!'));
        } else {
            var data = {
                totalPage: results[1],
                questionList: results[2]
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }
    })
};

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   start   */
exports.recommendQuestion = function (req, res) {

    var token = req.params.token;

    userService.getUserGagOrNotService(token, function (err, results) {
        if (err) {
            logger.error("Failed to recommendQuestion - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to recommendQuestion - " + err.message));
        } else {
            var gagOrNot = results._doc.gagOrNot;
            if(gagOrNot) {
                logger.error("Failed to recommendQuestion - " + gagOrNot);
                res.json(messageUtil.composeFailedMessage(req, "您被禁言了!" + ""));
            } else {
                logger.debug("Succeeded to recommendQuestion! - " + gagOrNot);

                var questionId = req.params.questionId;
                var flag = req.params.flag;

                questionService.recommendQuestionService(questionId, flag, function (err, result) {
                    if (err) {
                        logger.error('Exception happened when trying to recommendQuestion ...!' + err.message);
                        res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to recommendQuestion...!'));
                    } else {
                        res.json(messageUtil.composeSucceededMessage(req, null, null));
                    }
                })
            }
        }
    });
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   end   */

exports.searchUserQuestion = function (req, res) {
    var userId = req.params.userId;

    questionService.searchUserQuestionService(userId, function (err, results) {
        if (err) {
            logger.error('Exception happened when trying to searchUserQuestion ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to searchUserQuestion...!'));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }
    })
};


exports.getFreshNewsQuestion = function (req, res) {
    questionService.getFreshNewsQuestionService(function (err, result) {
        if (err) {
            logger.error('Exception happened when trying to getFreshNewsQuestion ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to getFreshNewsQuestion...!'));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};

exports.addQuestionToFreshNews = function (req, res) {
    var input = req.body;
    questionService.addQuestionToFreshNewsService(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying to addQuestionToFreshNews ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to addQuestionToFreshNews...!'));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

exports.pushQuestionByTag = function (req, res) {
    var question = req.body;

    questionService.pushQuestionByTagService(question, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying to pushQuestionByTag ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to pushQuestionByTag...!'));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};

exports.confirmPushQuestion = function (req, res) {

    var question = req.body.question;
    var data = req.body.uList;

    //个推
    var content = {
        type: 1,
        flag: 2,
        openType: 1,
        contentId: question._id,
        createdBy: question.createdBy._id,
        desc: question.createdBy.nickName + ':' + question.desc
    };
    var pushData = {
        uList: data,
        content: content,
        type: 'operate',
        tag: '话题'
    };
    toolUtil.putMessageGetuiPushMQ(pushData);

    res.json(messageUtil.composeSucceededMessage(req, null, null));
}

exports.changeQuestionCategory = function (req, res) {
    var questionId = req.params.questionId;
    var category = req.params.category;

    questionService.changeQuestionCategoryService(questionId, category, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying to changeQuestionCategory ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when trying to changeQuestionCategory...!'));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

exports.changeQuestionLevel = function (req, res) {
    var input = req.body;

    questionService.changeQuestionLevelService(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying to changeQuestionLevelService ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};


/**
 * 我的帖子1.6.0
 * @param req
 * @param res
 */
exports.myReleasedQuestions = function (req, res) {
    var token = req.params.token;
    var ts = req.params.ts;
    var vcode = req.query.vcode;

    questionService.myReleasedQuestionsService(token, ts, Number(vcode), function (err, result) {
        if (err) {
            logger.error('Exception happened when trying get myReleasedQuestions ...!' + err.message);
            res.json(messageUtil.composeErrorMessage(req, err, 4013));
        } else {
            var data = {
                ts: result.length > 0 ? result[result.length - 1].dateCreated.getTime() : (new Date("2000/04/01 00:00:00")).getTime(),
                questions: result
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data, 4013));
        }
    });
};

exports.myReplyQuestions = function (req, res) {
    var token = req.params.token;
    var ts = req.params.ts;

    questionService.myReplyQuestionsService(token, ts, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying get myReplyQuestions ...!' + err.message);
            res.json(messageUtil.composeErrorMessage(req, err, 4014));
        } else {
            var data = {
                ts: Number(ts) + 1,
                questions: result
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data, 4014));
        }
    })
};

/**
 * 我的收藏1.6.0
 * @param req
 * @param res
 */
exports.myFollowupQuestions = function (req, res) {
    var token = req.params.token;
    var ts = req.params.ts;
    var vcode = req.query.vcode;

    questionService.myFollowupQuestionsService(token, ts, Number(vcode), function (err, result) {
        if (err) {
            logger.error('Exception happened when trying get myFollowupQuestionsService ...!' + err.message);
            res.json(messageUtil.composeErrorMessage(req, err, 4015));
        } else {
            var data = {
                ts: result.length > 0 ? result[result.length - 1]._doc.followTime.getTime() : (new Date("2000/04/01 00:00:00")).getTime(),
                questions: result
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data, 4015));
        }
    })
};

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   start   */
/**
 * 问题点赞1.6.0
 * @param req
 * @param res
 */
// 点赞
exports.praiseQuestion = function (req, res) {
    var token = req.params.token;
    userService.getUserGagOrNotService(token, function (err, results) {
        if (err) {
            logger.error("Failed to praiseQuestion - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to praiseQuestion - " + err.message));
        } else {
            var gagOrNot = results._doc.gagOrNot;
            if(gagOrNot) {
                logger.error("Failed to praiseQuestion - " + gagOrNot);
                res.json(messageUtil.composeFailedMessage(req, "您被禁言了!" + ""));
            } else {
                logger.debug("Succeeded to praiseQuestion! - " + gagOrNot);

                var questionId = req.params.questionId;

                questionService.praiseQuestionService(token, questionId, function (err, result) {
                    if (err) {
                        logger.error('Exception happened when trying praiseQuestion ...!' + err.message);
                        res.json(messageUtil.composeErrorMessage(req, err, 4016));
                    } else {
                        var data = {
                            questionId: questionId,
                            praiseCount: result[1].count,
                            isPraise: true
                        };

                        res.json(messageUtil.composeSucceededMessage(req, null, data, 4016));

                        //统计用户数据
                        redisClient.HINCRBY(redisKey.getUserDataStatisticKey(result[1].createdBy), 'questionPraise', 1);

                        toolUtil.changeUserStatistics(result[1].createdBy, result[1].community, 'questionPraise', 1);

                        redisClient.HINCRBY(redisKey.getUserDataStatisticKey(token), 'praise', 1);

                        toolUtil.putMessageSmartRankMQ({questionId: questionId, type: 2, userId: token});

                        toolUtil.putMessageBusinessMQ({
                            msgType: 'praise',
                            userId: token,
                            contentId: questionId,
                            contentType: 'question'
                        })
                    }
                })
            }
        }
    });
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   end   */

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   start   */
/**
 * 问题取消点赞
 * @param req
 * @param res
 */
// 取消点赞
exports.cancelPraiseQuestion = function (req, res) {
    var token = req.params.token;
    userService.getUserGagOrNotService(token, function (err, results) {
        if (err) {
            logger.error("Failed to cancelPraiseQuestion - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to cancelPraiseQuestion - " + err.message));
        } else {
            var gagOrNot = results._doc.gagOrNot;
            if(gagOrNot) {
                logger.error("Failed to cancelPraiseQuestion - " + gagOrNot);
                res.json(messageUtil.composeFailedMessage(req, "您被禁言了!" + ""));
            } else {
                logger.debug("Succeeded to cancelPraiseQuestion! - " + gagOrNot);

                var questionId = req.params.questionId;

                questionService.cancelPraiseQuestionService(token, questionId, function (err, result) {
                    if (err) {
                        logger.error('Exception happened when trying cancelPraiseQuestion ...!' + err.message);
                        res.json(messageUtil.composeErrorMessage(req, err, 4017));
                    } else {
                        var data = {
                            questionId: questionId,
                            praiseCount: result[2].count,
                            isPraise: false
                        };
                        res.json(messageUtil.composeSucceededMessage(req, null, data, 4017));

                        //统计用户数据
                        redisClient.HINCRBY(redisKey.getUserDataStatisticKey(result[2].createdBy), 'questionPraise', -1);

                        redisClient.HINCRBY(redisKey.getUserDataStatisticKey(token), 'praise', -1);

                        //toolUtil.putMessageBusinessMQ({
                        //    msgType: 'praise',
                        //    userId: token,
                        //    contentId: questionId,
                        //    contentType: 'question'
                        //})
                    }
                })
            }
        }
    });
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   end   */

exports.praiseUsers = function (req, res) {
    var token = req.params.token;
    var ugcId = req.params.ugcId;
    var category = req.params.category;
    var ts = req.params.ts;

    questionService.praiseUsersService(ugcId, ts, category, token, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying praiseUsers ...!' + err.message);
            res.json(messageUtil.composeErrorMessage(req, err, 4018));
        } else {
            var data = {
                ts: result.length > 0 ? result[result.length - 1].praiseTime.getTime() : (new Date("2000/04/01 00:00:00")).getTime(),
                praiseList: result
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data, 4018));
        }
    })
};

/**
 * 其他用户的帖子1.6.0
 * @param req
 * @param res
 */
exports.otherReleasedQuestions = function (req, res) {
    var token = req.params.token;
    var ts = req.params.ts;
    var userId = req.params.userId;
    var communityId = req.query.communityId;

    questionService.otherReleasedQuestionsService(userId, token, ts, communityId, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying get otherReleasedQuestions ...!' + err.message);
            res.json(messageUtil.composeErrorMessage(req, err, 4019));
        } else {
            var data = {
                ts: result.length > 0 ? result[result.length - 1].dateCreated.getTime() : (new Date("2000/04/01 00:00:00")).getTime(),
                questions: result
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data, 4019));
        }
    });
};

/**
 * 1.7.0 新增问题（图片上传至七牛）
 * @param req
 * @param res
 */
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   start   */
// 发布问问
exports.addNewQuestion = function (req, res) {
    res.header("Access-Control-Allow-Origin", "*");
    /*宝宝树66小区二次改造    add   chenf  20170818  start*/
    var atDesc = "";
    /*宝宝树66小区二次改造    add   chenf  20170818  end*/
    var token = req.params.token;

    userService.getUserGagOrNotService(token, function (err, results) {
        if (err) {
            logger.error("Failed to addNewQuestion - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to addNewQuestion - " + err.message));
        } else {
            var gagOrNot = results._doc.gagOrNot;
            if(gagOrNot) {
                logger.error("Failed to addNewQuestion - " + gagOrNot);
                res.json(messageUtil.composeFailedMessage(req, "您被禁言了!" + ""));
            } else {
                logger.debug("Succeeded to addNewQuestion! - " + gagOrNot);

                var md5Key = 'app:question:md5';
                var md5Str = md5(JSON.stringify(req.body));

                redisClient.HGET(md5Key, token, function (err, value) {
                    if (value != null && value == md5Str) {
                        res.json(messageUtil.composeFailedMessage(req, '不可以发重复内容哦～', 4020));
                    } else {
                        var input = req.body;
                        if (input.category == 'free') {
                            input.category = 'secondhand'
                        }
                        var oldDesc = input.desc;

                        if (input.category != 'question') {
                            delete input.score;
                        }

                        if (input.desc == null || input.desc == '') {
                            res.json(messageUtil.composeErrorMessage(req, {message: '发布内容不能为空'}, 4020));
                        } else {
                            /*宝宝树66小区二次改造    add   chenf  20170818  start*/
                            var atDesc = input.desc;
                            /*宝宝树66小区二次改造    add   chenf  20170818  end*/
                                questionService.replaceUgcDescAtService(input.desc, input.uList, function (err, desc) {
                                input.desc = desc;

                                questionService.addNewQuestionService(token, input, function (err, result) {
                                    if (err) {
                                        logger.error('Exception happened when addNewQuestion ...!' + err.message);
                                        res.json(messageUtil.composeErrorMessage(req, err, 4020));
                                    } else {

                                        /*宝宝树66小区二次改造    add   chenf  20170818  start 追加@功能*/
                                        //@功能
                                        if (input.uList != null && typeof input.uList == 'string') {
                                            input.uList = [input.uList];
                                        }
                                        if (input.uList != null && input.uList.length > 0 && atDesc.indexOf(atFlag) != -1) {
                                            questionService.replyAtService(result[0], "", input.uList, 'question', token, atDesc);
                                        }
                                        /*宝宝树66小区二次改造    add   chenf  20170818  end 追加@功能*/

                                        toolUtil.putMessageSmartRankMQ({questionId: result[0]._id, type: 1});

                                        //发布内容md5
                                        redisClient.HSET(md5Key, token, md5(JSON.stringify(req.body)));
                                        redisClient.TTL(md5Key, function (err, value) {
                                            if (value == -1) {
                                                redisClient.EXPIRE(md5Key, toolUtil.getExpireTime());
                                            }
                                        });

                                        var data = {
                                            _id: result[0]._id
                                        };

                                        var action = (input.category == 'question' || input.category == 'secondhand') ? 23 : 3;

                                        toolUtil.hessianInvokeAddScore(token, action, null, function (score) {
                                            logger.info(score)

                                            if (input.images != null) {
                                                console.log("newQuestion.images", input.images);
                                                data.images = input.images;
                                            }
                                            data.dateCreated = result[0].dateCreated;

                                            data.shareData = shareService.shareDataService(result[1] + "的" + questionCategory[result[0].category],
                                                result[0].desc, result[0].images, 'question');

                                            if (result[0].topicId != null) {
                                                data.topicUrl = h5Host + '/app/topic/index.html?tid=' + result[0].topicId;
                                            }


                                            data.shareUrl = 'http://' + backOfficeHost + QUESTION_SHARE_URL + '?v=1.0';

                                            if (score != null && score.currentValue != null && score.currentValue != 0) {
                                                data.currentValue = score.currentValue;
                                                data.changeValue = score.changeValue;
                                                res.json(messageUtil.composeSucceededMessage(req, "发布成功", data, 4020));
                                            } else {
                                                res.json(messageUtil.composeSucceededMessage(req, "发布成功", data, 4020));
                                            }


                                            //清楚缓存
                                            var key = 'catch:q:all:' + result[0].community;
                                            var categoryKey = 'catch:q:category:' + input.category + ':' + result[0].community;
                                            redisClient.del(key);
                                            redisClient.del(categoryKey);


                                            if (input.score != null && input.score != 0) {
                                                toolUtil.hessianInvokeAddScore(token, 21, -input.score, function (value) {
                                                })
                                            }


                                            //统计用户数据
                                            redisClient.HINCRBY(redisKey.getUserDataStatisticKey(token), 'question', 1);
                                            toolUtil.changeUserStatistics(token, result[0].community, 'question', 1);

                                            if (input.key != null) {
                                                redisClient.zadd(input.key, result[0].dateCreated.getTime(), JSON.stringify({
                                                    _id: result[0]._id + '',
                                                    category: result[0].category
                                                }));

                                                var arr = input.key.split(':');

                                                var message = {
                                                    msgType: 'iwant',
                                                    contentId: result[0]._id + '',
                                                    contentType: 'question',
                                                    moudle: arr[2],
                                                    userId: token,
                                                    community: result[0].community,
                                                    isExistAt: oldDesc.indexOf(atFlag) != -1 && input.uList != null && input.uList.length > 0 ? 1 : 0,
                                                    atUidList: input.uList
                                                };
                                                if (arr[3] != null) {
                                                    message.condition = arr[3];
                                                }

                                                //推送
                                                toolUtil.putMessageBusinessMQ(message)

                                            } else {
                                                //推送
                                                console.log("推送: ", input.category);

                                                if (input.category == 'alert') {
                                                    console.log("push: ", input.category);

                                                    toolUtil.putMessageBusinessMQ({
                                                        msgType: 'emergency_alert',
                                                        contentId: result[0]._id + '',
                                                        contentType: 'alert'
                                                    })
                                                } else if (input.category in ['question', 'secondhand', 'recommendation'])
                                                    console.log("push: ", input.category);

                                                toolUtil.putMessageBusinessMQ({
                                                    msgType: 'question4help',
                                                    contentId: result[0]._id + '',
                                                    contentType: 'question',
                                                    // isExistAt: oldDesc.indexOf(atFlag) != -1 && input.uList != null && input.uList.length > 0 ? 1 : 0,
                                                    // atUidList: input.uList
                                                })
                                            }
                                        }, req.query.vcode);
                                    }
                                })
                            });
                        }
                    }
                });
            }
        }
    });
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   end   */

exports.otherReplyQuestions = function (req, res) {
    var token = req.params.token;
    var ts = req.params.ts;
    var userId = req.params.userId;

    questionService.otherReplyQuestionsService(userId, token, ts, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying get otherReplyQuestions ...!' + err.message);
            res.json(messageUtil.composeErrorMessage(req, err, 4021));
        } else {
            var data = {
                ts: Number(ts) + 1,
                questions: result
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data, 4021));
        }
    })
};

/**
 * 1.7.0 问题回复
 * @param req
 * @param res
 */
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   start   */
// 回复
exports.addNewReply = function (req, res) {
    res.header("Access-Control-Allow-Origin", "*");
    var token = req.params.token;

    userService.getUserGagOrNotService(token, function (err, results) {
        if (err) {
            logger.error("Failed to addNewReply - " + err.message);
            res.json(messageUtil.composeFailedMessage(req, "Failed to addNewReply - " + err.message));
        } else {
            var gagOrNot = results._doc.gagOrNot;
            if(gagOrNot) {
                logger.error("Failed to addNewReplyn - " + gagOrNot);
                res.json(messageUtil.composeFailedMessage(req, "您被禁言了!" + ""));
            } else {
                logger.debug("Succeeded to addNewReply! - " + gagOrNot);

                var input = req.body;
                var questionId = req.params.questionId;

                var md5Key = 'app:reply:md5';
                var md5Str = md5(JSON.stringify(req.body));

                var lang = req.cparams.lang;

                redisClient.HGET(md5Key, token + ':' + questionId, function (err, value) {
                    if (value != null && value == md5Str) {

                        var msg =  (lang && lang == 'en_US') ?
                            ErrorMessage.REPEATED_CONTENTS.message_en_US : ErrorMessage.REPEATED_CONTENTS.message;

                        res.json(messageUtil.composeFailedMessage(req, msg, 4022));
                    } else {

                        input.replyDesc = input.replyDesc.trim();

                        if (input.replyDesc == '' && (input.images == null || input.images.length == 0)) {
                            var msg =  (lang && lang == 'en_US') ?
                                ErrorMessage.EMPTY_CONTENTS.message_en_US : ErrorMessage.EMPTY_CONTENTS.message;

                            res.json(messageUtil.composeFailedMessage(req, msg, 4022));
                            return;
                        }

                        input.replyDesc = input.replyDesc.substr(0, 2000);
                        input.replyDesc = input.replyDesc.replace(/[\uD800-\uDBFF]$/, '');

                        questionService.addNewReplyService(token, questionId, input, function (err, result) {
                            if (err) {
                                logger.error('Exception happened when addNewQuestion ...!' + err.message);
                                res.json(messageUtil.composeErrorMessage(req, err, 4022));
                            } else {

                                //发布内容md5
                                redisClient.HSET(md5Key, token + ':' + questionId, md5(JSON.stringify(req.body)));
                                redisClient.TTL(md5Key, function (err, value) {
                                    if (value == -1) {
                                        redisClient.EXPIRE(md5Key, 120);
                                    }
                                });

                                var question = result[3];
                                var replyId = {
                                    _id: question.replies[question.replies.length - 1]._id,
                                    reply: question.replies[question.replies.length - 1],
                                    replyCountStr: toolUtil.transformNumber(question.replies.length)
                                };

                                if (replyId.reply.replyTo == null) replyId.reply.replyTo = undefined;

                                if (result[0].createdBy + '' == token) {
                                    res.json(messageUtil.composeSucceededMessage(req, "回复成功", replyId, 4022));
                                } else {

                                    var action = question.category == 'question' ? 7 : 4;

                                    if (question.replies.length == 1 && question.category == 'question' && question.replies[0].dateReplied.getTime() - question.dateCreated.getTime() < 300000) {
                                        action = 16;
                                    }

                                    var replyMsg = action == 16 ? '抢答成功' : '回复成功';

                                    //回复加分
                                    toolUtil.hessianInvokeAddScore(token, action, null, function (score) {
                                        if (score != null && score.currentValue != null && score.currentValue != 0) {
                                            replyId.currentValue = score.currentValue;
                                            replyId.changeValue = score.changeValue;
                                            res.json(messageUtil.composeSucceededMessage(req, replyMsg, replyId, 4022));
                                        } else {
                                            res.json(messageUtil.composeSucceededMessage(req, replyMsg, replyId, 4022));
                                        }
                                    }, req.query.vcode);
                                }


                                //统计用户数据
                                redisClient.HINCRBY(redisKey.getUserDataStatisticKey(token), 'questionReply', 1);
                                /*  宝宝树66小区二次改造    mod   chenf  20170822   start   个人页数据统计修改*/
                                /*toolUtil.changeUserStatistics(token, result[1], 'questionReply', 1)*/
                                toolUtil.changeUserStatisticsNew(token,'questionReply', 1);
                                /*  宝宝树66小区二次改造    mod   chenf  20170822   start   个人页数据统计修改*/

                                //清除缓存
                                var key = 'catch:q:all:' + result[0].community;
                                var categoryKey = 'catch:q:category:' + question.category + ':' + result[0].community;
                                redisClient.del(key);
                                redisClient.del(categoryKey);
                                redisClient.del('question:reply:list:' + questionId);


                                //@功能
                                if (input.uList != null && typeof input.uList == 'string') {
                                    input.uList = [input.uList];
                                }
                                if (input.uList != null && input.uList.length > 0 && input.replyDesc.indexOf(atFlag) != -1) {
                                    questionService.replyAtService(result[0], replyId._id, input.uList, 'question', token, input.replyDesc);
                                }
                                //推送参与回复用户
                                if (input.replyTo == null && input.replyDesc.indexOf(atFlag) == -1) {
                                    /*  宝宝树66小区二次改造    mod   chenf  20170802   start   */
                                    /*toolUtil.putMessageQAMQ({
                                        msgType: 'reply2reply',
                                        uid: token,
                                        questionId: result[0]._id + '',
                                        replyDesc: input.replyDesc,
                                        contentType: 'question'
                                    });*/
                                    input.replyTo = result[0].createdBy.toString();
                                }


                                /*toolUtil.putMessageSmartRankMQ({questionId: result[0]._id, type: 3});*/
                                /*  宝宝树66小区二次改造    mod   chenf  20170802   start   */


                                //敏感词过滤
                                toolUtil.filteringSensitiveWords(result[0]._id, replyId._id, input.replyDesc, 'question', function (err, replyDesc) {
                                    //推送

                                    logger.info('push----reply')

                                    toolUtil.putMessageQAMQ({
                                        msgType: 'reply',
                                        isExistAt: input.uList != null && input.uList.length > 0 ? 1 : 0,
                                        atUidList: input.uList,
                                        replyUid: token,
                                        topicId: result[0]._id + '',
                                        replyId: replyId._id + '',
                                        replyDesc: replyDesc,
                                        contentType: 'question',
                                        /*  宝宝树66小区二次改造    mod   chenf  20170802   start   */
                                        /*isAsk: input.replyTo == null ? 0 : 1,*/
                                        isAsk: 0,
                                        /*  宝宝树66小区二次改造    mod   chenf  20170802   end   */
                                        toReplyUid: input.replyTo
                                    });
                                });
                            }
                        })
                    }
                });
            }
        }
    });

};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170802   end   */


exports.getTopic = function (req, res) {
    var input = req.params;

    questionService.getTopic(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying get getTopic ...!' + err.message);
            res.json(messageUtil.composeErrorMessage(req, err, 4023));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 4023));
        }
    })
};

exports.getShareByTopicId = function (req, res) {
    var input = req.params;

    questionService.getShareByTopicId(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when trying get getShareByTopicId ...!' + err.message);
            res.json(messageUtil.composeErrorMessage(req, err, 4024));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 4024));
        }
    })
};
